function addCommas(str) {
    var amount = new String(str);
    amount = amount.split('').reverse();
    var output = "";
    for (var i = 0; i <= amount.length - 1; i++) {
        output = amount[i] + output;
        if ((i + 1) % 3 == 0 && (amount.length - 1) !== i) output = ',' + output;
    }
    return output;
}

function emptyCart() {
    $.ajax({
        url: 'hiti_ajax/empty_cart',
        type: 'POST',
        cache: false,
        data: null,
        success: function() {
            $('.cart_content').fadeOut(function() {
                $('.removeCartAll').parent().hide();
                $('.mini_empty').fadeIn();
                $('.slcart, .subtotal').html(0);
                $('#btnThanhtoan').fadeOut();
            });
        }
    });
}

function updateThanhtoan() {
    var thuevat = 0.0;
    var phi_giaohang = 0.0;
    var coupon = 0.0;
    var tongcong = 0.0;
    var tien_thanhtoan = 0.0;
    if ($('.tongcong').length) tongcong = parseInt($('.tongcong').html().replace(/,/g, ''));
    if ($('.vat').length) thuevat = parseInt($('.vat').html().replace(/,/g, ''));
    if ($('.coupon').length) coupon = parseInt($('.coupon').html().replace(/,/g, ''));
    if ($('.phi_giaohang').length) phi_giaohang = parseInt($('.phi_giaohang').html().replace(/,/g, ''));
    tien_thanhtoan = tongcong + thuevat + phi_giaohang - coupon;
    if ($('.tien_thanhtoan').length) $('.tien_thanhtoan').html(addCommas(tien_thanhtoan));
}

function checkSoluong(e) {
    var sl = $(e).val();
    if (sl == "0")
    {
        $(e).val(1);
    }
    else if (isNaN(sl) == true)
    {
        $(e).val(1);
    }
}


function shopping_cart() {
    $.ajax({
        url: site_url + 'hiti_ajax/shopping_cart',
        type: 'POST',
        cache: false,
        data: null,
        success: function(string) {
            var getData = $.parseJSON(string);
            $('.slcart').html(getData.numCart);
            $('.subtotal').html(getData.total);
            if (parseInt($('.slcart').html()) != 0) {
                $('#mini_cart .mini_empty').hide();
                $('#mini_cart .mini_footer').show();
                $('#mini_cart .mini_container').html(getData.content);
            } else {
                $('#mini_cart .mini_empty').fadeIn();
                $('#mini_cart .mini_footer').hide();
            }
        }
    });
}

function footer_carts_show(){
    shopping_cart();
    $('.footer_carts_body').css({height:'auto'});
    $('.footer_carts_showbtn').hide();
    $('.footer_carts_hidebtn').fadeIn();
}

function footer_carts_hide(){
    $('.footer_carts_body').css({height:'0px'});
    $('.footer_carts_hidebtn').hide();
    $('.footer_carts_showbtn').fadeIn();
}

function addToCart(id, sl, kthuoc, color) {
    if (kthuoc == null) kthuoc = '';
    if (color == null) color = '';
    if ($('#sl').length)
    {
        if (sl == 0 || sl < 0 || isNaN(sl))
        {
            showErrOfField('sl', 'sl');
            return false;
        }
    }
    $('.addCart').attr('disabled', true);
    $('.addCart').html($('#lng_processing').html());
    $.ajax({
        url: site_url + 'hiti_ajax/add_cart',
        type: 'POST',
        cache: false,
        data: {
            id: id,
            sl: sl,
            kthuoc: kthuoc,
            color: color
        },
        success: function(string) {
            $('.slcart').html(string);
            $('.addCart').html($('#lng_added_cart').html());
            $('#item_name'+id).addClass('cart_ok');
            if ($('#sl').length)
            {
                $('#sl').val();
            }
            if ($('.orderpart_checkoutlink').length)
            {
                $('.orderpart_checkoutlink').fadeIn();
            }
            setTimeout(function() {
                $('#item_name'+id).removeClass('cart_ok');
                $('.addCart').html($('#lng_buy_now').html());
                $('.addCart').attr('disabled', false);
            }, 2000);
        },
    });
}

$(function() {
	$('.phuongthuc_thanhtoan').click(function() {
        var phuongthuc = $(this).data('value');
        $('#phuongthuc_thanhtoan').val(phuongthuc);
    });

    $('.remove_cart a').bind('click', function() {
        var id = $(this).data('id');
        $.ajax({
            url: 'hiti_ajax/remove_cart',
            type: 'POST',
            cache: false,
            data: {
                id: id
            },
            success: function(string) {
                var getData = $.parseJSON(string);
                $('.slcart').html(getData.numCart);
                $('.subtotal').html(getData.total);
                updateThanhtoan();
                $('.CardItem' + id).fadeOut(function() {
                    $(this).remove();
                    if (parseInt($('.slcart').html()) == 0) {
                        $('.removeCartAll').parent().hide();
                        $('#btnThanhtoan').fadeOut();
                        $('.mini_empty').fadeIn();
                    }
                });
            }
        });
    });

    if (parseInt($('.slcart').html()) != 0) $('.mini_empty').hide();

    $('.btnAddCart').click(function() {
        var id = $(this).data('id');
        var productItem = $(this).parent().parent().parent().parent().parent().parent().parent().parent();
        var sl = productItem.find('.inputPrice').val();
        $.ajax({
            url: site_url + 'hiti_ajax/add_cart',
            type: 'POST',
            cache: false,
            data: {
                id: id,
                sl: sl
            },
            success: function(string) {
                productItem.addClass('cart_ok');
                setTimeout(function() {
                    productItem.removeClass('cart_ok');
                }, 3000);
            },
        });
        return false;
    });

    $('.removeCartAll').bind('click', emptyCart);

    $('.mini_qty').bind('keyup keydown', function() {
        var id = $(this).attr('data-id');
        var qty = $(this).val().trim();
        if (isNaN(qty)) {
            $(this).val(1);
            return false;
        }
        if (qty != '' && qty > 0) {
            $.ajax({
                url: site_url + 'hiti_ajax/update_cart',
                type: 'POST',
                cache: false,
                data: {
                    id: id,
                    qty: qty,
                },
                success: function(string) {
                    var getData = $.parseJSON(string);
                    $('.CartTotal' + id).html(getData.thanhtien);
                    $('.subtotal').html(getData.total);
                }
            });
        }
    });

    $('#order_confirm').click(function() {
        var maxacthuc = $('#maxacthuc').val();
        var ma = $('.orders_code').html();
        if (maxacthuc == '') {
            showErrOfField('maxacthuc', 'maxacthuc');
            return false;
        }
        $('#order_confirm span').html(lng_procesing);
        $('input[type="text]').attr('disabled', true);
        $.ajax({
            url: site_url + 'hiti_ajax/order_confirm',
            type: 'POST',
            cache: false,
            data: {
                ma: ma,
                maxacthuc: maxacthuc
            },
            success: function(string) {
                if (string == '1')
                {
                    $('.order_status').html('<span style="color: green">ĐÃ XÁC NHẬN</span>');
                    $('.order_confirm').fadeOut();
                }
                if (string == '0')
                {
                    showErrOfField('maxacthuc_fail', 'maxacthuc');
                    $('#order_confirm span').html($('#lng_confirm_order').text());
                }
            }
        });
        return false;
    });

    var inProcessDatHang = 0;
    $('#checkoutFrm').bind('submit', function() {
        
        if (inProcessDatHang == 1) {
            Avgrund.show("#inProcess-popup");
            return false;
        } else {

            key = /^\w+(\.\w+)*@\w+\.\w+(\.\w+)?$/;
            var orders_code = $('.orders_code').html();
            if ($('#checkoutFrm .phi_giaohang').length) var phi_giaohang = $('#checkoutFrm .phi_giaohang').html().replace(/,/g, '');
            if ($('#checkoutFrm .vat').length) var vat = $('#checkoutFrm .vat').html().replace(/,/g, '');
            var ten_nguoimua = $('#checkoutFrm #ten_nguoimua').val();
            var dienthoai_nguoimua = $('#checkoutFrm #dienthoai_nguoimua').val();
            var diachi_giaohang = $('#checkoutFrm #diachi_giaohang').val();
            var phuongthuc_thanhtoan = $('#checkoutFrm #phuongthuc_thanhtoan').val();
            var email_nguoimua = $('#checkoutFrm #email_nguoimua').val();
            var khachhang_ghichu = $('#checkoutFrm #khachhang_ghichu').val();
            var address_city = $('#checkoutFrm #address_city').val();
            var address_district = $('#checkoutFrm #address_district').val();
            var address_ward = $('#checkoutFrm #address_ward').val();
            var tongcong = $('#checkoutFrm .tongcong').html().replace(/,/g, '');
            var tien_thanhtoan = $('#checkoutFrm .tien_thanhtoan').html().replace(/,/g, '');
            var congty = $('#checkoutFrm #congty').val();
            var diachi_congty = $('#checkoutFrm #diachi_congty').val();
            var masothue = $('#checkoutFrm #masothue').val();

            if (ten_nguoimua == '') {
                showErrOfField('ten_nguoimua', 'ten_nguoimua');
                return false;
            }
            if (email_nguoimua == '') {
                showErrOfField('email_nguoimua_empty', 'email_nguoimua');
                return false;
            }
            if (!key.test(email_nguoimua)) {
                showErrOfField('email_nguoimua_fail', 'email_nguoimua');
                return false;
            }
            if (dienthoai_nguoimua == '' || dienthoai_nguoimua.length < 8 || dienthoai_nguoimua.length > 12 || isNaN(dienthoai_nguoimua)) {
                showErrOfField('dienthoai_nguoimua', 'dienthoai_nguoimua');
                return false;
            }
            if (diachi_giaohang == '' || diachi_giaohang.length < 8) {
                showErrOfField('diachi_giaohang', 'diachi_giaohang');
                return false;
            }
            if (address_city == '') {
                showErrOfField('address_city', 'address_city');
                return false;
            }
            if (address_district == '' && $('#address_city option').length > 1) {
                showErrOfField('address_district', 'address_district');
                return false;
            }
            if (address_ward == '' && $('#address_ward option').length > 1) {
                showErrOfField('address_ward', 'address_ward');
                return false;
            }
            if ($('#vat_request').is(':checked')) {
                if (congty == '' || congty.length < 8) {
                    showErrOfField('congty', 'congty');
                    return false;
                }
                if (diachi_congty == '' || diachi_congty.length < 8) {
                    showErrOfField('diachi_congty', 'diachi_congty');
                    return false;
                }
                if (masothue == '' || masothue.length < 10 || masothue.length > 30) {
                    showErrOfField('masothue', 'masothue');
                    return false;
                }
            }

            inProcessDatHang = 1;
            // Avgrund.show("#inProcess-popup");
             $('.frm_item button[type="submit"] span').html('Đang xử lý...');
             $('.input-div input').attr('disabled', '');
            $.ajax({
                url: site_url + 'hiti_ajax/hoantat_hoadon',
                type: 'POST',
                cache: false,
                data: {
                    ten_nguoimua: ten_nguoimua,
                    dienthoai_nguoimua: dienthoai_nguoimua,
                    diachi_giaohang: diachi_giaohang,
                    phuongthuc_thanhtoan: phuongthuc_thanhtoan,
                    email_nguoimua: email_nguoimua,
                    khachhang_ghichu: khachhang_ghichu,
                    orders_code: orders_code,
                    phi_giaohang: phi_giaohang,
                    vat: vat,
                    tongcong: tongcong,
                    tien_thanhtoan: tien_thanhtoan,
                    address_city: address_city,
                    address_district: address_district,
                    address_ward: address_ward,
                    congty: congty,
                    diachi_congty: diachi_congty,
                    masothue: masothue
                },
                success: function(string) {
                    if (string != 0)
                    {
                        window.location = string;
                    }
                    else
                    {
                        //Avgrund.hide();
                       // Avgrund.show("#thanhToanOk-popup");
                        //$('.btn-avgrund-close').bind('click', function() {
                           // Avgrund.hide();
                           $('.frm_item button[type="submit"] span').html('HOÀN TẤT ĐẶT HÀNG');
                           alert('Bạn đã đặt hàng thành công');
                           window.location = './trang-chu.html';
                        //});
                        inProcessDatHang = 0;
                        setTimeout(function() {
                            Avgrund.hide();
                            window.location = './trang-chu.html';
                        }, 4000);
                    }
                }
            });
            return false;
        }
        return false;
    });
	
	if ($('#address_city').length) {
        $.ajax({
            url: site_url + 'hiti_ajax/load_city',
            type: 'POST',
            cache: false,
            data: {
                show: 1,
                parent: 0
            },
            success: function(string) {
                var getData = $.parseJSON(string);
                for (var c in getData) {
                    $('#address_city').append('<option value="' + getData[c].id + '" data-price="' + getData[c].price + '">' + getData[c].name_vn + '</option>');
                }
            }
        });

        $('#address_city').change(function(e) {
            $('#address_district').children('option').remove();
            if ($(this).val() != '') {
                var parent = $(this).val();
                if (parent != 271) {
                    $('#phuongthuc_thanhtoan0').attr('checked', false).attr('disabled', true);
                } else {
                    $('#phuongthuc_thanhtoan0').attr('disabled', false);
                }
                if ($('.phi_giaohang').length) {
                    var price = $('#address_city option[value="' + parent + '"]').attr('data-price');
                    $('.phi_giaohang').html(addCommas(price));
                    updateThanhtoan();
                }
                $.ajax({
                    url: site_url + 'hiti_ajax/load_city',
                    type: 'POST',
                    cache: false,
                    data: {
                        show: 1,
                        parent: parent
                    },
                    success: function(string) {
                        var getData = $.parseJSON(string);
                        for (var d in getData) {
                            $('#address_district').append('<option value="' + getData[d].id + '" data-price="' + getData[d].price + '">' + getData[d].name_vn + '</option>');
                        }
                    }
                });
            }
        });

        $('#address_district').change(function(event) {
            var parent = $(this).val();
            if ($(this).val() != '') {
                var parent = $(this).val();
                if ($('.phi_giaohang').html() != null) {
                    var price = $('#address_district option[value="' + parent + '"]').attr('data-price');
                    $('.phi_giaohang').html(addCommas(price));
                    updateThanhtoan();
                }
                $.ajax({
                    url: site_url + 'hiti_ajax/load_city',
                    type: 'POST',
                    cache: false,
                    data: {
                        show: 1,
                        parent: parent
                    },
                    success: function(string) {
                        var getData = $.parseJSON(string);
                        if (getData != null) {
                            for (var w in getData) {
                                $('#address_ward').append('<option value="' + getData[w].id + '" data-price="' + getData[w].price + '">' + getData[w].name_vn + '</option>');
                            }
                        }
                    }
                });
            }
        });

        $('#address_ward').change(function(event) {
            if ($(this).val() != '') {
                var parent = $(this).val();
                if ($('.phi_giaohang').html() != null) {
                    var price = $('#address_ward option[value="' + parent + '"]').attr('data-price');
                    $('.phi_giaohang').html(addCommas(price));
                    updateThanhtoan();
                }
            }
        });
    }
});